<template>
	<view class="login">
		<cu-custom bgImage="" :isBack="true">
			<block slot="backText"></block>
			<block slot="content">登陆</block>
		</cu-custom>
		<view class="content">
			<!-- 头部logo -->
			<view class="header" :style="{marginTop:marginTop}">
				<image :src="logoImage"></image>
			</view>
			<!-- 主体表单 -->
			<view class="main " v-if="!isWeChat">
				<wInput v-model="phone" :phone="phone" type="text" maxlength="11" placeholder="手机号"></wInput>
				<wInput v-model="code" type="password" maxlength="11" placeholder="验证码"></wInput>
			</view>

			<wButton class="wbutton" :text="btnText" :rotate="isRotate" @click="startLogin" fontColor="#333333"></wButton>

			<!-- 其他登录 -->
			<!-- <view class="other_login cuIcon">
				<view class="login_icon">
					<view :class="cuIcon" @tap="login_weixin"></view>
				</view>
			</view> -->

			<!-- 底部信息 -->
			<!-- <view class="footer">
				<text>其他方式登陆</text>
			</view> -->
		</view>
	</view>
</template>

<script>
	var _this;
	import wInput from '@/components/watch-input.vue' //input
	import wButton from '@/components/watch-button.vue' //button
	import { mapMutations } from "vuex"
	export default {
		data() {
			return {
				//logo图片 base64
				logoImage: '',
				phone: '', //用户/电话
				code: '', //密码
				isRotate: false, //是否加载旋转
				isWeChat: false, //是否是选择微信授权登陆
				btnText: "登 陆",
				user: {
					phone: null,
					code: null
				},
				userStatus:{
					isLogin:false,
					phone:"",
				},
				userInfo: {},
				baseURL: getApp().globalData.baseURL,
				marginTop: "128rpx",
				cuIcon: "cuIcon-weixin"
			};
		},
		components: {
			wInput,
			wButton,
		},
		mounted() {
			_this = this;
			//this.isLogin();
		},
		methods: {
			...mapMutations("user", ["setStatus","setUser"]),
			isLogin() {
				//判断缓存中是否登录过，直接登录
				// try {
				// 	const value = uni.getStorageSync('setUserData');
				// 	if (value) {
				// 		//有登录信息
				// 		console.log("已登录用户：",value);
				// 		_this.$store.dispatch("setUserData",value); //存入状态
				// 		uni.reLaunch({
				// 			url: '../../../pages/index',
				// 		});
				// 	}
				// } catch (e) {
				// 	// error
				// }
			},
			//发送验证码
			sendCode() {
				uni.showToast({
					title: "发送中...",
					icon: "loading"
				})

				uni.request({
					url: this.baseURL + `/getSMS/getSms`,
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					method: 'POST',
					data: {
						phone: this.phone
					},
					success: (res) => {
						console.log(res)
						uni.showToast({
							title: "发送成功!",
							icon: "none"
						})
					},
					fail: (res) => {
						uni.showToast({
							title: "发送失败!",
							icon: "none"
						})
					}
				})
			},

			
			//登陆成功后的操作
			successLogin(data){
				
				uni.setStorageSync('Auth',this.userStatus)
				this.$store.commit("user/setStatus", this.userStatus)
				this.$store.commit("user/setUser", data)
				uni.showToast({
					title:"登陆成功~",
					icon:"none",
					duration:500
					
				})
				setTimeout(function(){
					uni.navigateBack({
						delta:1
					})
				},500)
			},

			//确认登陆
			startLogin(e) {
				// console.log(e)
				let that = this
				//登录
				if (this.isRotate) {
					//判断是否加载中，避免重复点击请求
					return false;
				}
				if (this.phone.length == "") {
					uni.showToast({
						icon: 'none',
						position: 'bottom',
						title: '手机号不能为空'
					});
					return;
				}
				if (this.code.length != 6) {
					uni.showToast({
						icon: 'none',
						position: 'bottom',
						title: '验证码不正确'
					});
					return;
				}
				this.user.phone = this.phone
				this.user.code = this.code
				_this.isRotate = true
				
				this.userStatus.isLogin = true
				this.userStatus.phone = this.phone
				that.successLogin(this.userInfo)
				// try {
				// 	uniCloud.callFunction({
				// 		name: 'selectUser',
				// 		data: {
				// 			phone: this.phone
				// 		}
				// 	}).then((res) => {
				// 		if(res.result.data.length==0)
				// 		{
				// 			that.initUser() //初始化用户信息
				// 			uniCloud.callFunction({
				// 				name:'add',
				// 				data:this.userInfo
				// 			}).then((res)=>{
				// 				console.log("add:",res)
				// 				that.successLogin(this.userInfo)
				// 			}).catch((err) => {
				// 				uni.showModal({
				// 					content: `操作失败：${err.message}`,
				// 					showCancel: false
				// 				})
				// 			})
				// 		}else{
				// 			that.successLogin(res.result.data[0])
				// 		}
						
				// 		console.log(res)
				// 	}).catch((err) => {
				// 		uni.hideLoading()
				// 		uni.showModal({
				// 			content: `操作失败：${err.message}`,
				// 			showCancel: false
				// 		})
				// 		console.error(err)
				// 	})
				    
				// } catch (e) {
				// 	uni.showToast({
				// 		title:"登陆异常，请重试...",
				// 		duration:1000
				// 	})
				//     // error
				// }
				// uni.request({
				// 	url: this.baseURL + `/user/login`,
				// 	method: 'POST',
				// 	data:JSON.stringify(this.user),
				// 	success: (res) => {
				// 		console.log("成功返回结果：",res)
				// 	},
				// 	complete(res) {
				// 		console.log("完成：", res)
				// 	}
				// })


				// setTimeout(function() {
				// 	_this.isRotate = false
				// 	uni.navigateTo({
				// 		url:"../Store/index/index"
				// 	})
				// }, 3000)
				// uni.showLoading({
				// 	title: '登录中'
				// });
				// getLogin()
				// .then(res => {
				// 	//console.log(res)
				// 	//简单验证下登录（不安全）
				// 	if(_this.phoneData==res.data.username && _this.passData==res.data.password){
				// 		let userdata={
				// 			"username":res.data.username,
				// 			"nickname":res.data.nickname,
				// 			"accesstoken":res.data.accesstoken,
				// 		} //保存用户信息和accesstoken
				// 		_this.$store.dispatch("setUserData",userdata); //存入状态
				// 		try {
				// 			uni.setStorageSync('setUserData', userdata); //存入缓存
				// 		} catch (e) {
				// 			// error
				// 		}
				// 		uni.showToast({
				// 			icon: 'success',
				// 			position: 'bottom',
				// 			title: '登录成功'
				// 		});
				// 		uni.reLaunch({
				// 			url: '../../../pages/index',
				// 		});
				// 	}else{
				// 		_this.passData=""
				// 		uni.showToast({
				// 			icon: 'error',
				// 			position: 'bottom',
				// 			title: '账号或密码错误，账号admin密码admin'
				// 		});
				// 	}
				// 	uni.hideLoading();
				// }).catch(err => {
				// 	uni.hideLoading();
				// })

			},
			login_weixin() {
				//微信登录
				if (!this.isWeChat) {
					this.cuIcon = "cuIcon-mobilefill"
					this.isWeChat = true
					this.marginTop = "400rpx"
					this.btnText = "微信授权登陆"
				} else {
					this.cuIcon = "cuIcon-weixin"
					this.isWeChat = false
					this.marginTop = "128rpx"
					this.btnText = "登 陆"
				}


				uni.showToast({
					icon: 'none',
					position: 'bottom',
					title: '...'
				});
			},
			initUser(){
				this.userInfo.phone = this.phone
				this.userInfo.nickname = this.phone
				this.userInfo.avatar = "https://vkceyugu.cdn.bspapp.com/VKCEYUGU-minitask/dce9b210-1434-11eb-899d-733ae62bed2f.jpg"
				this.userInfo.university = "未选择"
				this.userInfo.injoin = this.tick()
				this.userInfo.level = "1"
				this.userInfo.grow = "0"
				this.userInfo.integral = "0"
				this.userInfo.hot = "0"
				this.userInfo.fans = "0"
				this.userInfo.follow = "0"
				this.userInfo.collection = "0"
				this.userInfo.unused = "0"
				this.userInfo.task = "0"
				
				// this.userInfo = {
				// 	phone: "17625495599",
				// 	nickname: "奇怪的上单",
				// 	avatar: "http://img2.imgtn.bdimg.com/it/u=1039075865,3371165857&fm=26&gp=0.jpg",
				// 	university: "北京大学",
				// 	injoin: "2020-10-22 15:36:25",
				// 	level: "1",
				// 	grow: "65",
				// 	integral: "421",
				// 	hot: "15"
				// }
			},
			tick() {
				let date = new Date();
				this.year = date.getFullYear();
				this.month = date.getMonth() + 1;
				this.date = date.getDate();
				this.hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
				this.minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
				this.second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
				let currentTime =  this.year + "/" + this.month + "/" + this.date + this.hour + ":" + this.minute + ":" + this.second;
				 return currentTime
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import url("@/components/css/icon.css");
	@import url("./css/main.css");

	.login {
		height: 100vh;
		overflow: hidden;
		position: relative;

		.content {}
	}
</style>
